/**
 * Created by lupf on 2016/4/28.
 */

angular.module('myApp')

    .controller('queryCtrl',['$scope', '$http', '$httpParamSerializerJQLike', '$log', 'OpenService', 'CheckboxService',
        'CacheService', 'limitToFilter', 'filterFilter', 'dateFilter', 'myConstant', function ($scope, $http, $httpParamSerializerJQLike, $log, OpenService, CheckboxService,
                                       CacheService, limitToFilter, filterFilter, dateFilter, myConstant) {
        //视图层变量viewModel
        var vm = $scope.vm = {};
        vm.constant = myConstant;
        //变量初始化
        //分页数据
        vm.pagination = {
            pageSize: 10,
            pageNum: 1
        };
        //查询条件
        vm.queryBean = {};

        //缓存数据初始化(需要缓存的key请自定义)
        /*数据格式{
         key1 :value1,
         key2:value2
         }*/
        vm.cached = {
            MERCHANT_CODE: {},
            SPECIALLY_AUDIT_STATUS: {}
        };

        (function initCache() {

            CacheService.getObj('ALL_CITY', function (key, cacheObj) {
                vm.cached['ALL_CITY'] = cacheObj;
            });
            CacheService.getObj('MCC_CODE', function (key, cacheObj) {
                vm.cached['MCC_CODE'] = cacheObj;
            });

            CacheService.initCaches(vm.cached);
        }());

        /*将前面缓存的数据格式化
         [{key:value},{key:value}]*/
        vm.getCache = function (key) {
            return CacheService.getCache(key);
        };

        //特约商户数据字典
            vm.cache = {
                MERCHANT_PROPERTY: {},
                MERCHANT_TYPE: {},
                PO_CREDENTIALS_TYPE: {},
                LEGAL_CREDENTIALS_TYPE: {},
                MERCHANT_STATUS: {},
                CHARGE_TYPE:{},
                SUPPORT_ACCOUNT_TYPE:{},
                EXPANSION_MODE:{},
                COMPLIANCE_RISK:{},
                OPEN_SERVICE_TYPE:{},
                ADDRESS_Select:{},
                ALL_AREA_CODE: {},
                CLEARING_NETWORK:{}
            };
//批量获取缓存
            var keys = [];
            for (var key in  vm.cache) {
                keys.push(key);
            }
            $log.debug('批量查询缓存');
            $http.post(config.ctx + '/specially/dataDic/cache/get', keys, config.jsonHeader)
                .then(function (response) {
                    var tempMap = response.data.object;
                    for (var key in vm.cache) {
                        if (!angular.isUndefined(tempMap[key])) {
                            vm.cache[key] = tempMap[key];
                        }
                    }
                }, function (response) {
                    $log.error('获取数据%s失败', keys);
                });



        //获取对象数据[user,user,user]
        vm.getObj = function (key, input) {
            return $http.post(config.ctx + '/base/cache/getAll',
                $httpParamSerializerJQLike({cacheKey: key}))
                .then(function (response) {
                    return limitToFilter(filterFilter(response.data.object, input), 6);
                }, function (response) {
                    $log.error('获取数据%s失败', cacheKey);
                })
        };

        vm.queryDetail = queryDetail;
        vm.resetForm = resetForm;

        /*------------------以上配置通用---------------------*/


        vm.updateItem = updateItem;
        vm.deleteItem = deleteItem;
        vm.uploadDetail = uploadDetail;

        /*------------------以上方法名可选择性通用---------------------*/

        /*CacheService.initCache(vm.cached, function (cacheKey, cacheObj) {
         $log.debug(cacheKey, cacheObj);
         vm.cached[cacheKey] = cacheObj;
         });*/

        /*vm.getCache = function (key) {
         CacheService.getCache(key)
         }*/

        function queryDetail() {
            var queryForm = document.getElementById('queryForm');
            vm.url = angular.element(queryForm).prop('action');

            //组织参数：查询条件 + 分页数据
            var postData = angular.copy(vm.queryBean);
            postData.pageSize = vm.pagination.pageSize;
            postData.pageNum = vm.pagination.pageNum;
            postData.beginTime = dateFilter(postData.beginTime, 'yyyy-MM-dd');
            postData.endTime = dateFilter(postData.endTime, 'yyyy-MM-dd');
            $http.post(vm.url, $httpParamSerializerJQLike(postData))
                .then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        vm.pagination = data.object;
                        //清空选中记录
                        CheckboxService.clearChecked();
                    } else {
                        alert(data.msg);
                    }
                });

        };

        function resetForm() {
            vm.queryBean = {};
        }

        function updateChecked($event, id) {
            CheckboxService.updateChecked($event, id);
            $log.debug(id);
            $log.debug(CheckboxService.getChecked());
        }


        function updateItem(cusCode) {
            console.info(vm.cached.ALL_AREA_CODE);
            var item;
            $http.post('mchntData', $httpParamSerializerJQLike({'cusCode': cusCode}))
                .then(function (response) {
                    var data = response.data;
                    if (data.success) {
                       item=data.object;
                        console.info("上报次数："+item.note);
                        console.info(item);

                        console.log('ready to open second.');
                        OpenService({
                            modalTitle: '编辑上报',
                            modalBody: 'toUpload',
                            url: 'upload',
                            item: item,
                            cached: {
                                ALL_AREA_CODE:vm.cache.ALL_AREA_CODE,
                                MERCHANT_PROPERTY:vm.cache.MERCHANT_PROPERTY,
                                PO_CREDENTIALS_TYPE:vm.cache.PO_CREDENTIALS_TYPE,
                                LEGAL_CREDENTIALS_TYPE:vm.cache.LEGAL_CREDENTIALS_TYPE,
                                MERCHANT_STATUS:vm.cache.MERCHANT_STATUS,
                                CHARGE_TYPE:vm.cache.CHARGE_TYPE,
                                SUPPORT_ACCOUNT_TYPE:vm.cache.SUPPORT_ACCOUNT_TYPE,
                                EXPANSION_MODE:vm.cache.EXPANSION_MODE,
                                COMPLIANCE_RISK:vm.cache.COMPLIANCE_RISK,
                                CLEARING_NETWORK:vm.cache.CLEARING_NETWORK,
                                MERCHANT_TYPE:vm.cache.MERCHANT_TYPE,
                                OPEN_SERVICE_TYPE:vm.cache.OPEN_SERVICE_TYPE,
                                SPECIALLY_AUDIT_STATUS:vm.cache.SPECIALLY_AUDIT_STATUS
                            }
                        }, function (item) {
                            vm.queryDetail();
                        },'updateMerchantInfoModalInstanceCtrl','myModalNoFooter.html');


                    } else {
                        alert("操作失败");
                    }
                }, function (response) {
                    alert(response.statusText);
                    $log.debug("error");
                });

        }

            // function uploadDetail(cusCode) {
            //
            //
            //     var item;
            //     $http.post('mchntData', $httpParamSerializerJQLike({'cusCode': cusCode}))
            //         .then(function (response) {
            //             var data = response.data;
            //             if (data.success) {
            //                 item = data.object;
            //                 console.info(item);
            //                 console.log('ready to open second.');
            //                 OpenService({
            //                     modalTitle: '查看详情',
            //                     modalBody: 'toDetail',
            //                     url: '#',
            //                     item: item,
            //                     cached: {
            //                         ALL_AREA_CODE: vm.cache.ALL_AREA_CODE,
            //                         MERCHANT_PROPERTY: vm.cache.MERCHANT_PROPERTY,
            //                         PO_CREDENTIALS_TYPE: vm.cache.PO_CREDENTIALS_TYPE,
            //                         LEGAL_CREDENTIALS_TYPE: vm.cache.LEGAL_CREDENTIALS_TYPE,
            //                         MERCHANT_STATUS: vm.cache.MERCHANT_STATUS,
            //                         CHARGE_TYPE: vm.cache.CHARGE_TYPE,
            //                         SUPPORT_ACCOUNT_TYPE: vm.cache.SUPPORT_ACCOUNT_TYPE,
            //                         MERCHANT_TYPE: vm.cache.MERCHANT_TYPE,
            //                         EXPANSION_MODE: vm.cache.EXPANSION_MODE,
            //                         COMPLIANCE_RISK: vm.cache.COMPLIANCE_RISK,
            //                         SPECIALLY_AUDIT_STATUS: vm.cache.SPECIALLY_AUDIT_STATUS
            //                     }
            //                 }, function (item) {
            //                 }, '', 'myModalNoSave.html');
            //
            //
            //             } else {
            //                 alert("操作失败");
            //             }
            //         }, function (response) {
            //             alert(response.statusText);
            //             $log.debug("error");
            //         });
            // }
        function uploadDetail(cusCode,note) {
            var item;
            $http.post('uploadDetail', $httpParamSerializerJQLike({'cusCode': cusCode,'note': note}))
                .then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        item=data.object;
                        console.info(item);
                        console.log('ready to open second.');
                        OpenService({
                            modalTitle: '查看详情',
                            modalBody: 'toUploadDetail',
                            url: '#',
                            item: item,
                            cached: {
                                ALL_AREA_CODE:vm.cache.ALL_AREA_CODE,
                                MERCHANT_PROPERTY:vm.cache.MERCHANT_PROPERTY,
                                PO_CREDENTIALS_TYPE:vm.cache.PO_CREDENTIALS_TYPE,
                                LEGAL_CREDENTIALS_TYPE:vm.cache.LEGAL_CREDENTIALS_TYPE,
                                MERCHANT_STATUS:vm.cache.MERCHANT_STATUS,
                                CHARGE_TYPE:vm.cache.CHARGE_TYPE,
                                SUPPORT_ACCOUNT_TYPE:vm.cache.SUPPORT_ACCOUNT_TYPE,
                                MERCHANT_TYPE:vm.cache.MERCHANT_TYPE,
                                EXPANSION_MODE:vm.cache.EXPANSION_MODE,
                                COMPLIANCE_RISK:vm.cache.COMPLIANCE_RISK,
                                SPECIALLY_AUDIT_STATUS:vm.cached.SPECIALLY_AUDIT_STATUS
                            }
                        }, function (item) {
                        },'uploadEnterpriseMchntBaseInfoDetail','myModalNoSave.html');
                    } else {
                        alert(response.data.msg);
                    }
                }, function (response) {
                    alert(response.statusText);
                    $log.debug("error");
                });
        }

        function deleteItem() {
            if (CheckboxService.getChecked().length != 1) {
                alert("必须勾选一条记录！");
                return;
            }
            $http.post('delete', $httpParamSerializerJQLike({'userId': CheckboxService.getChecked()[0]}))
                .then(function (response) {
                    var data = response.data;
                    if (data.success) {
                        var item = vm.pagination.list.filter(function (item, index, array) {
                            return item.userId == CheckboxService.getChecked()[0];
                        })[0];
                        vm.pagination.list.splice(vm.pagination.list.indexOf(item), 1);
                        alert("操作成功");
                    } else {
                        alert("操作失败");
                    }
                }, function (response) {
                    alert(response.statusText);
                    $log.debug("error");
                });
        }
    }]);

angular.module('myApp').controller('uploadEnterpriseMchntBaseInfoDetail',['$scope', '$uibModalInstance', 'modalItem', '$http',
        '$httpParamSerializerJQLike', '$log', 'dateFilter', 'myConstant', function ($scope, $uibModalInstance, modalItem, $http,
    $httpParamSerializerJQLike, $log, dateFilter, myConstant) {

            var vm = $scope.vm = {
            modalTitle: 'please change the title',
            modalBody: '#',
                detail:"",
            url: '',
            item: {},
            cached:{}
        };

        vm = $scope.vm = modalItem;
        vm.constant = myConstant;

        console.info(vm.item);

        vm.uploadMchntDetail = function uploadMchntDetail(id) {
                 console.info(id);
                vm.detail=id;
        };
        vm.closeUploadMchntDetail = function closeUploadMchntDetail(id) {
            if(vm.detail!=id){
                return;
            }
            vm.detail=-1;
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };
    }]);

angular.module('myApp').controller('updateMerchantInfoModalInstanceCtrl',['$scope', '$uibModalInstance', 'modalItem', '$http',
    '$httpParamSerializerJQLike', '$log', 'dateFilter', 'myConstant', function ($scope, $uibModalInstance, modalItem, $http,
                                                                                    $httpParamSerializerJQLike, $log, dateFilter, myConstant) {

    var vm = $scope.vm = {
        modalTitle: 'please change the title',
        modalBody: '#',
        url: '',
        item: {}
    };

    console.log(modalItem);
    vm = $scope.vm = modalItem;
    vm.constant = myConstant;
        $scope.networkTypes=  eval('(' + vm.item.networkTypeForJS + ')');
        $scope.openTypes=  eval('(' + vm.item.openTypeForJS + ')');
        var netSelected;
        var openSelected;
        if(vm.item.networkType!=null&&vm.item.networkType!=""){
            netSelected =vm.item.networkType.split(",") ;
        }else {
            netSelected=[];
        }
        if(vm.item.openType!=null&&vm.item.openType!=""){
            console.info(vm.item.openType);
            openSelected =vm.item.openType.split(",") ;
        }else {
            openSelected=[];
        }
        $scope.isNetChecked = function(id){
            return netSelected.indexOf(id) >= 0 ;
        };
        $scope.isOpenChecked = function(id){
            return openSelected.indexOf(id) >= 0 ;
        };
        $scope.updateSelection = function($event,id){
            var boo=netSelected.indexOf(id)>= 0;
            if(boo){
                var index= netSelected.indexOf(id);
                netSelected.remove(index);
                console.info("去掉的id："+index);
            }else {
                netSelected.push(id);
                console.info("增加的id："+id);
            }
            console.info("数组里已有的："+netSelected);
        } ;
        $scope.updateOpenSelection = function($event,id){
            var boo=openSelected.indexOf(id)>= 0;
            if(boo){
                var index= openSelected.indexOf(id);
                openSelected.remove(index);
                console.info("去掉的id："+index);
            }else {
                openSelected.push(id);
                console.info("增加的id："+id);
            }
            console.info("数组里已有的："+openSelected);
        } ;
        $scope.save = function () {
        // console.info("原数据："+vm.item.areaList[0]);
        var postData = angular.copy(vm.item);
        postData.startTime = dateFilter(postData.startTime, 'yyyy-MM-dd');
        postData.endTime = dateFilter(postData.endTime, 'yyyy-MM-dd');
        postData.occurarea="";
        for(var i=0;i<postData.areaList.length;i++){
            if(postData.areaList[i].code!=null&&postData.areaList[i].code!=""){
                postData.occurarea=postData.occurarea+","+postData.areaList[i].code;
            }
        }
        console.info("清算网络："+netSelected);
        postData.networkType=netSelected.join(",");
        postData.openType=openSelected.join(",");
            if(postData.occurarea.length>1){
                postData.occurarea= postData.occurarea.substr(1);
            }else {
                postData.occurarea = "";
            }
        console.info("地区范围"+postData.occurarea);
        console.info(postData.areaList);
        console.info("哈哈哈哈");
        delete postData.pageNum;
        delete postData.pageSize;
        delete postData.rowCount;
        delete postData.areaList;
        delete postData.clearKey;
        delete postData.$$hashKey;
        delete postData.auditFailNote;
        $log.debug(postData);
        $http.post(vm.url, postData ,config.jsonHeader)
            .then(function (response) {
                if (response.data.success) {
                    alert("操作成功");
                    $uibModalInstance.close(vm.item);
                } else {
                    alert(response.data.msg);
                }
            }, function (response) {
                alert("操作失败");
                alert(response.status);
            })
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

          console.info(vm.item.areaList);
            if( vm.item.areaList==null||vm.item.areaList==""){
                vm.item.areaList=[];
                if(vm.item.occurarea!=null&&vm.item.occurarea!=""){
                    var area=vm.item.occurarea.split(",");
                    for(var i=0;i<area.length;i++){
                        vm.item.areaList[i]={"code": area[i]};
                    }
                }else {
                    vm.item.areaList[0]={"code": ""};
                }
        }
        vm.addOccurarea = function addOccurarea(obj) {
            console.log("addOccurarea");
            vm.item.areaList.push({"code": ""});
        };
        vm.deleteOccurarea = function deleteOccurarea(index) {
            if (index == 0) {
                alert("第一条信息不能删除!");
            } else {
                vm.item.areaList.remove(index);
            }
        };

        Array.prototype.remove = function (dx) {
            if (isNaN(dx) || dx > this.length) {
                return false;
            }
            for (var i = 0, n = 0; i < this.length; i++) {
                if (this[i] != this[dx]) {
                    this[n++] = this[i]
                }
            }
            this.length -= 1
        };

}]);